<template>
	<view class="video-device-form">
		<!-- 	<view class="header">
			<img src="../../static/arrow.png" alt="" class="back-img" />
			<text class="header-title">传感器上传</text>
		</view> -->
		<!-- 边设备信息 -->
		<view class="video-device-container">
			<view class="form-header">
				<text>边设备信息</text>
			</view>
			<view class="video-device-info">
				<view class="info-item-large">
					<text class="label">边设备ID:</text>
					<!-- <uni-easyinput v-model="station.fileDeviceId" :clearable="false" trim="true"></uni-easyinput> -->
					<uni-data-select v-model="fileDeviceId" @change="selectDevice()" :localdata="deviceOptions"
						placeholder="请导入台账后选择边设备" />
				</view>
				<view class="info-item-large">
					<text class="label">用户名:</text>
					<uni-easyinput v-model="fileUsername" :clearable="false" trim="true"></uni-easyinput>
				</view>
				<view class="info-item-large">
					<text class="label">密码:</text>
					<uni-easyinput v-model="filePwd" :clearable="false" trim="true"></uni-easyinput>
				</view>
			</view>
		</view>

		<uni-popup style="width: 500px;" ref="editDialog" type="dialog">
			<uni-popup-dialog style="width: 400px;" title="编辑传感器" :before-close="true" @close="closeeEdit()"
				@confirm="confirmEdit()">
				<uni-forms style="width: 400px;" ref="mForm" :modelValue="editDevice" class="form-container-box">
					<uni-forms-item label-width="80px" label="设备名称" required name="name" class="info-item">
						<uni-easyinput :clearable="false" v-model="editDevice.name" />
					</uni-forms-item>

					<uni-forms-item label-width="80px" label="设备标识" required name="sn" class="info-item">
						<uni-easyinput disabled v-model="editDevice.sn" placeholder="请输入设备标识" />
					</uni-forms-item>

					<uni-forms-item label-width="80px" label="设备类型" required name="type" class="info-item">
						<uni-data-select disabled v-model="editDevice.type" :localdata="deviceTypes"
							placeholder="当前无设备类型" />
					</uni-forms-item>

					<uni-forms-item label-width="80px" label="设备地址" required name="comaddr" class="info-item">
						<uni-easyinput disabled v-model="editDevice.comaddr" placeholder="请输入设备地址" />
					</uni-forms-item>

					<uni-forms-item label-width="80px" label="COM口" required name="comno" class="info-item">
						<uni-data-select disabled v-model="editDevice.comno" :localdata="portOptions"
							placeholder="当前无串口" />
					</uni-forms-item>

					<uni-forms-item label-width="80px" label="平台设备" required name="iotid" class="info-item">
						<uni-data-select v-model="editDevice.iotid" :localdata="platformOptions"
							placeholder="请选择平台设备名称" />
					</uni-forms-item>
				</uni-forms>
			</uni-popup-dialog>
		</uni-popup>



		<!-- 模拟编辑按钮 -->
		<!-- 	<button type="primary" class="btnl" @click="simulateEdit()">
			<view class="icon-container">
				
			</view>模拟编辑
		</button> -->


		<!-- 端设备列表 -->
		<view class="end-device-list">
			<view class="header-box">
				<view class="flex">
					<view class="form-header">端设备列表</view>
					<button type="primary" class="add-camera-btn" @click="clickGetSensor()">
						<view class="icon-container">
							<image src="../../static/data.png" mode="" class="icon"></image>
						</view>获取数据
					</button>

				</view>
				<view class="flex">
					<button type="primary" class="scan-btn" @click="importExcel()">
						导入平台台账
					</button>
				</view>
			</view>

			<view>
			</view>

			<view class="end-device-container">
				<view class="device-item" v-for="(device, index) in deviceList" :key="index">
					<view class="device-header">
						<view v-if="device.iotid!==''" class="red-triangle"></view>
						<view class="device-text">{{ device.name }}</view>
						<view class="device-buttons">
							<button type="primary" class="edit-btn" @click="showEditDialog(device)">编辑</button>
							<!-- <button type="primary" class="more-btn">更多数据</button> -->
						</view>
					</view>
					<view class="device-content">
						<view class="device-detail" v-for="(detail, dIndex) in device.points" :key="dIndex">
							<text class="text-detail">{{ detail.name }}: </text>
							<text class="text-detail">{{ detail.value }}</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 按钮栏 -->
		<!-- <view class="button-bar"> -->
		<button type="primary" class="btnl" @click="saveConf()">
			<view class="icon-container">
				<image src="../../static/check.png" mode="" class="icon"></image>
			</view>保存配置
		</button>
		<!-- </view> -->
	</view>


</template>

<script setup lang="ts">
	import { ref, onMounted, reactive } from 'vue'
	import { WEB_URL } from '../../config/global';
	import { onLoad } from '@dcloudio/uni-app';
	import * as XLSX from 'xlsx';
	import { getJsonData } from '../../js_sdk/file';
	const mForm = ref()
	const deviceList = ref([])
	const editDevice = ref()
	const editDialog = ref()
	//台账列表
	const tzArray = ref([])
	//台账前置主机列表
	const tzZJArray = ref([])
	//台账传感器列表
	const tzSensorArray = ref([])
	const deviceOptions = ref([])
	const inputDialog = ref()
	const plateformData = ref()
	const station = ref()
	const fileDeviceId = ref('')
	const fileUsername = ref()
	const filePwd = ref()
	const addDialogRef = ref()
	const formData = ref({
		deviceName: "",
		deviceId: "",
		deviceType: "",
		deviceAddress: "",
		devicePort: "",
	})


	const mockDevice = {
		name: "传感器A",
		sn: "SN123456789",
		type: "温度传感器",
		comaddr: "/dev/ttyUSB0",
		comno: "COM1",
		platformDeviceName: "平台设备A"
	};



	const platformOptions = ref([])
	const backUpPlatformOptions = ref([])

	const deviceTypes = [{
		text: '温湿度',
		value: '00'
	},
	{
		text: '水浸',
		value: '01'
	},
	{
		text: '烟感',
		value: '02'
	},
	{
		text: '气体传感器',
		value: '03'
	},
	{
		text: '门磁',
		value: '04'
	},
	{
		text: '水位传感器',
		value: '05'
	},
	{
		text: '风机',
		value: '06'
	},
	{
		text: '水泵',
		value: '07'
	},
	{
		text: '蓄电池',
		value: '08'
	},
	{
		text: '空调控制器',
		value: '09'
	},
	];

	const protocolTypes = [{
		text: '协议1',
		value: 'protocol1'
	},
	{
		text: '协议2',
		value: 'protocol2'
	}
	];

	const portOptions = [{
		text: 'COM1',
		value: 'COM1'
	},
	{
		text: 'COM2',
		value: 'COM2'
	},
	{
		text: 'COM3',
		value: 'COM3'
	},
	{
		text: 'COM4',
		value: 'COM4'
	}
	];

	const rules = {
		deviceName: {
			rules: [{
				required: true,
				errorMessage: '设备名称不能为空'
			}]
		},
		deviceId: {
			rules: [{
				required: true,
				errorMessage: '设备标识不能为空'
			}]
		},
		deviceType: {
			rules: [{
				required: true,
				errorMessage: '请选择设备类型'
			}]
		},
		deviceAddress: {
			rules: [{
				required: true,
				errorMessage: '串口地址不能为空'
			}]
		},
		devicePort: {
			rules: [{
				required: true,
				errorMessage: '请选择COM口'
			}]
		}
	};

	// const simulateEdit = () => {
	// 	// 模拟选择一个设备并打开编辑弹窗
	// 	showEditDialog(mockDevice);
	// };

	const showEditDialog = (device) => {
		// editDevice.value = { ...device }; // 使用深拷贝避免直接修改原始数据
		editDevice.value = device
		editDialog.value.open()
	}

	const saveConf = async () => {
		uni.showModal({
			title: '提示',
			content: '是否确认保存配置?',
			confirmText: "确定",
			cancelText: "取消",
			showCancel: true,
			success: (res) => {
				if (fileDeviceId.value == '') {
					uni.showModal({
						title: '提示',
						content: '请先导入台账并选择边设备',
						confirmText: "确定",
						showCancel: false,
					})
				}

				let edge = {
					iotip: plateformData.value.platformIP,
					iotport: plateformData.value.platformPort,
					iotid: fileDeviceId.value,
					iotuser: fileUsername.value,
					iotpwd: filePwd.value,
				}
				let sensor = []
				for (let i = 0; i < deviceList.value.length; i++) {
					let obj = { id: deviceList.value[i].id, iotid: deviceList.value[i].iotid }
					sensor.push(obj)
				}

				let data = { edge: edge, sensor: sensor }
				let param = { data: data }
				console.log("param", param);
				uni.request({
					url: WEB_URL + '/app/updateSensor',
					data: param,
					method: 'POST',
					header: {
						'Content-Type': 'application/json'
					},
					dataType: 'json',
					success: async (res) => {
						if (res.data.code === 0) {
							uni.showToast({
								title: '上传配置成功',
								icon: 'success'
							})
							await getSensor()
						} else {
							uni.showModal({
								title: '提示',
								content: res.data.message,
								confirmText: "确定",
								showCancel: false,
							})
						}

					},
					fail: (err) => {
						uni.showModal({
							title: '提示',
							content: '保存失败，系统异常',
							confirmText: "确定",
							showCancel: false,
						})
					},
				})
			}
		})

	}


	const open = () => {
		inputDialog.value.open()
	}

	const closeeEdit = () => {
		editDialog.value.close()
	}

	const confirmEdit = () => {
		// console.log('editDevice', editDevice.value);
		uni.showToast({
			title: '修改成功',
			icon: 'success'
		})
		editDialog.value.close()
	}

	const close = () => {
		formData.value.deviceName = ""
		formData.value.deviceId = ""
		formData.value.deviceType = ""
		formData.value.deviceAddress = ""
		formData.value.devicePort = ""
		inputDialog.value.close()
	}

	const add = async () => {
		const valid = await mForm.value.validate();
		if (valid) {
			let param = {
				name: formData.value.deviceName,
				sn: formData.value.deviceId,
				comaddr: formData.value.deviceAddress,
				type: formData.value.deviceType,
				comno: formData.value.devicePort
			}
			deviceList.value.push(param)
			close()
		}
	}
	const addDialog = () => {
		// uni.navigateTo({
		// 	url: "/pages/addSensor/addSensor"
		// })
		inputDialog.value.open()
	}

	const selectDevice = () => {
		platformOptions.value = backUpPlatformOptions.value
		let device = tzArray.value.filter((e) => {
			return e.clientId === fileDeviceId.value
		})
		fileUsername.value = device[0].username
		filePwd.value = device[0].password
		let deviceName = device[0].deviceName

		let target = deviceName.substring(0, deviceName.indexOf('#'))
		let name = target.replace(/[0-9]/g, '')

		platformOptions.value = platformOptions.value.filter((e) => {
			return e.text.includes(name)
		})
	}

	onLoad(async (options) => {
		if (!Object.keys(options).length == 0) {
			station.value = JSON.parse(decodeURIComponent(options.item))
		}
		let filePath2 = '_doc/test/platform.json'
		let dataJson2 = await getJsonData(filePath2)
		if (dataJson2 === '') {
		} else {
			plateformData.value = JSON.parse(dataJson2);
		}

		// station.value = {
		// 	videoData: {
		// 		videoPort: 8000,
		// 		videoUsername: "admin",
		// 		videoPassword: "njzt12345"
		// 	},
		// 	gatewayData: {
		// 		gatewayIP: "192.168.1.168",
		// 		gatewayPort: 8000,
		// 		gatewayPassword: 'njzt12345'
		// 	}
		// }
		await getSensor()

	});

	const clickGetSensor = async () => {
		await getSensor()
		uni.showToast({
			title: '获取成功',
			icon: 'success'
		})
	}

	const getSensor = () => {
		return new Promise((resolve, reject) => {
			uni.request({
				url: WEB_URL + '/app/getSensor',
				method: 'GET',
				success: (res) => {
					if (res.data.code === 0) {
						deviceList.value = res.data.data
						resolve('suc');
					} else {
						uni.showModal({
							title: '提示',
							content: res.data.message,
							confirmText: "确定",
							showCancel: false,
						})
					}
				},
				fail(err) {
					uni.showModal({
						title: '提示',
						content: '系统错误',
						confirmText: "确定",
						showCancel: false,
					})
					reject('err')
				}
			})
		})
	}


	const importExcel = () => {
		//选择文件
		const filePicker = uni.requireNativePlugin('Ba-FilePicker')
		filePicker.selectFile({
			'selectType': 0,
			'maxCount': 1,
			'filetypes': 'xlsx,xls'
		}, (ret) => {
			if (ret.data) {
				//解析文件
				console.log('tzArray.value', tzArray.value);
				plus.io.requestFileSystem(plus.io.PUBLIC_DOCUMENTS, fs => { //请求文件系统
					fs.root.getFile(
						ret.data[0].absolutePath, //请求文件的地址
						{
							create: false //当文件不存在时创建
						}, fileEntry => {
							fileEntry.file(function (file) {
								//new一个可以用来读取文件的对象fileReader
								let fileReader = new plus.io.FileReader();
								fileReader.readAsDataURL(file)
								fileReader.onerror = e => { //读文件失败
									console.log("获取文件失败", fileReader.error);
									plus.nativeUI.toast("获取文件失败,请重启应用", {
										background: "#ffa38c",
										duration: 2000
									});
									return;
								};
								fileReader.onload = e => { //读文件成功
									console.log("读取excel成功", e);
									const model = /.*base64,/
									const newFile = e.target.result.replace(model, '');
									const workbook = XLSX.read(newFile, { type: 'base64' })
									//excel解析
									getFileData(workbook.Sheets.sheet1)
									plus.nativeUI.toast('导入成功', {
										background: "#ffa38c",
										duration: 2000
									})
								};
							});
						}, error => {
							console.log("2新建获取文件失败", error);
							plus.nativeUI.toast("获取文件失败,请重启应用", {
								background: "#ffa38c",
								duration: 2000
							});
							return;
						});
				},
					e => {
						console.log("1请求文件系统失败", e.message);
						plus.nativeUI.toast("请求系统失败,请重启应用", {
							background: "#ffa38c",
							duration: 2000
						});
						return;
					}
				);
			}
		});

		/**
		 * 解析平台台账
		 */
		const getFileData = (sheet) => {
			let cl = sheet["!ref"]
			let index = cl.indexOf(":");
			let max = parseInt(cl.substr(index + 2, cl.length))
			// console.log('sheet', sheet);
			tzZJArray.value = []
			tzArray.value = []
			tzSensorArray.value = []
			deviceOptions.value = []
			platformOptions.value = []
			for (let i = 2; i <= max; i++) {
				let obj : any = {}
				for (let j = 1; j <= 6; j++) {
					if (j == 1) {
						obj.productName = sheet["A" + i.toString()]["v"]
						if (sheet["A" + i.toString()]["v"].toString().includes('主机') || sheet["A" + i.toString()]["v"].toString().includes('前置')) {
							obj.password = sheet["F" + i.toString()]["v"]
						}
					}
					if (j == 2) {
						obj.deviceName = sheet["B" + i.toString()]["v"]
					}
					if (j == 2) {
						obj.clientId = sheet["C" + i.toString()]["v"]
					}
					if (j == 4) {
						obj.sn = sheet["D" + i.toString()]["v"]
					}
					if (j == 5) {
						obj.username = sheet["E" + i.toString()]["v"]
					}
				}
				if (obj.productName.includes('前置主机')) {
					tzZJArray.value.push(obj)
					let option = { text: obj.deviceName, value: obj.clientId }
					deviceOptions.value.push(option)
				} else {
					tzSensorArray.value.push(obj)
					let option2 = { text: obj.deviceName, value: obj.clientId }
					platformOptions.value.push(option2)
					backUpPlatformOptions.value.push(option2)
				}
				tzArray.value.push(obj)
			}
		}

	}
</script>

<style>
	.red-triangle {
		width: 0;
		height: 0;
		border-left: 10px solid transparent;
		border-right: 10px solid transparent;
		border-bottom: 10px solid red;
		position: absolute;
		top: 0;
		left: 0;
		z-index: 10;
		-webkit-transform: rotate(-45deg);

	}



	/* 基本样式 */
	.video-device-form {
		padding: 45px 20px;
		background-color: #f7f7f7;
		/* border-radius: 8px; */
		height: 100vh;

	}

	/deep/.uni-popup-dialog .uni-popup-dialog__wrapper {
		width: 600px !important;

		/* padding: 40rpx; */
	}

	.text-detail {
		font-style: normal;
		font-size: 14px;
	}

	.header {
		/* border: 1px solid red; */
		display: flex;
		justify-content: center;
		align-items: center;
		padding-bottom: 20px;
		position: relative;
	}

	.back-img {
		position: absolute;
		left: 0;
	}

	.header-title {
		font-size: 24px;
		color: #666;
	}

	.video-device-container {
		/* border: 1px solid red; */
		padding: 20px;
		background-color: #fff;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		border-radius: 5px;
	}

	.header-box {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.form-header {
		font-size: 24px;
		color: #666;
		margin-right: 20px;
	}

	.header-btn {
		display: flex;
		align-items: center;

	}

	.invider {
		width: 20px;
	}

	/* 视频设备信息样式 */
	.video-device-info {
		margin-top: 15px;
		/* display: grid;
		grid-template-columns: repeat(2, 1fr); */
		gap: 20px;
		/* 项目之间的间距 */
		margin-bottom: 5px;
	}

	.info-item {
		flex: 1 1 calc(50% - 20px);
		display: flex;
		align-items: center;
		gap: 10px;
	}

	.info-item-large {
		flex: 1 1 calc(50% - 20px);
		display: flex;
		align-items: center;
		gap: 10px;
		margin-bottom: 20px;
	}

	/* 当前行只有最后一个输入框时，让它占一半 */
	.video-device-info>.last-item:last-child {
		flex: 1 1 calc(50% - 20px);
	}

	.label {
		font-size: 18px;
		color: #666;
		width: 120px;
		text-align: right;
		flex-shrink: 0;
		padding-right: 10px;
	}

	.input {
		padding: 8px;
		border: 1px solid #ddd;
		border-radius: 4px;
		font-size: 18px;

	}

	.end-device-list {
		margin-top: 20px;
		background-color: #fff;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		border-radius: 5px;
		padding: 20px;
		margin-bottom: 20px;
	}

	.end-device-container {
		margin-top: 20px;
		/* border: 1px solid red; */
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 10px;
	}

	.device-item {
		border: 1px solid #ddd;
		border-radius: 8px;
		/* padding: 10px; */
		margin-bottom: 10px;
	}

	.device-header {
		/* border: 1px solid red; */
		background-color: #f3fbfb;
		border-top-right-radius: 8px;
		border-top-left-radius: 8px;
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-size: 16px;
		position: relative;
	}

	.device-text {
		padding: 0 10px;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		max-width: 160px;
	}

	.device-buttons {
		display: flex;
		gap: 10px;
		margin: 10px;
	}

	.edit-btn {
		font-size: 16px;
		background-color: #48b0b1 !important;
		/* color: white; */
		padding: 0 20px;
		border-radius: 4px;
	}

	.more-btn {
		font-size: 16px;
		background-color: #5a79ff !important;
		/* color: white; */
		/* padding: 0 10px; */
		border-radius: 4px;
	}

	.device-content {
		margin-top: 10px;
	}


	.device-detail {
		display: flex;
		align-items: center;
		padding: 5px 10px;
		margin-bottom: 5px;
	}

	/* 固定在底部的按钮栏 */
	.button-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		display: flex;
		justify-content: space-around;
		background-color: #fff;
		padding: 20px;
		z-index: 1000;
	}

	.flex {
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.import-btn {
		background-color: #48b0b1 !important;
	}

	.scan-btn {
		border-radius: 5px;
		background-color: #5a79ff !important;
		margin-right: 10px;
	}

	.save-setting-btn {
		border-radius: 5px;
		background-color: #5a79ff !important;
		/* margin-right: 10px; */
	}

	.fetch-btn {
		border-radius: 5px;
		background-color: #07c160 !important;
	}

	.btn-container {
		border-radius: 5px;
		padding: 0 10px;
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: #5a79ff !important;

		.icon-container {
			width: 20px;
			height: 20px;
		}

		.icon {
			width: 100%;
			height: 100%;
		}
	}

	.btn-container-fetch {
		border-radius: 5px;
		padding: 0 10px;
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: #07c160 !important;

		.icon-container {
			width: 20px;
			height: 20px;
		}

		.icon {
			width: 100%;
			height: 100%;
		}
	}

	.btnl {
		display: flex;
		justify-content: center;
		align-items: center;
		border-radius: 4px;
		font-size: 16px;
		width: 150px;
	}

	.add-channel-btn,
	.add-camera-btn {
		display: flex;
		justify-content: center;
		align-items: center;
		border-radius: 4px;
		font-size: 16px;
	}

	.add-channel-btn {
		background-color: #48b0b1 !important;
	}

	.add-camera-btn {
		background-color: #07c160 !important;
	}

	.icon-container {
		width: 20px;
		height: 20px;
		display: flex;
		justify-content: center;
		align-items: center;
		margin-right: 10px;
	}

	.icon {
		width: 100%;
		height: 100%;
	}

	.btn-text {
		font-size: 14px;
		margin-left: 10px;
	}

	.icon-box {
		width: 15px;
		height: 15px;
		display: flex;
		justify-content: center;
		align-items: center;

	}
</style>